package com.netty.esc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netty.esc.entity.model.UserInfoDTO;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhaoyang05
 * @Data: 2021/11/3 16:04
 * @Description
 */
@Component
public class TokenUtil {

   @Resource
   RedisTemplate<String,Object> redisTemplate;

    public static final String TOKEN = "login_user.token:";
    private static final String PHONE = "login_user.phone:";

    /**
     * jwt生成token
     * */
    public  String makeToken(String telephone){
        JwtUtils jwt = JwtUtils.getInstance();
        return jwt.setClaim(PHONE, telephone).generateToken();
    }

    /**
     * 生成token，存入redis中，设置七天失效时间
     * */
    public  String makeTokenInRedis(UserInfoDTO userInfoDTO){
        final String telephone = userInfoDTO.getTelephone();
        String token = makeToken(telephone);
        Map<String,Object> map = new HashMap<>();
        map.put("telephone",telephone);
        String s = JSON.toJSONString(map);
//        RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.opsForValue().set(TOKEN+telephone,s,7,TimeUnit.DAYS);
        return token;
    }

    /**
     * 解析token
     * */
    public  JSONObject tokenAnalysis(String token){
        JwtUtils jwt = JwtUtils.getInstance();
        Claims check = jwt.check(token);
        if (check==null){
            return null;
        }
        String msg = (String)redisTemplate.boundValueOps(TOKEN+check.get(PHONE)).get();
        if (msg==null){
            return null;
        }
        return JSONObject.parseObject(msg);

    }

}
